import { useEffect, useRef, useState } from "react";
/**
 * @description  监听元素是否进入视口
 * @param {IntersectionObserverInit} options - 监听选项
 * @returns {[React.MutableRefObject<T | null>, boolean]} [targetRef, isIntersecting]
 * @example
 * const [targetRef, isIntersecting] = useIntersectionObserver()
 * <div ref={targetRef}>
 *   {isIntersecting ? 'Visible' : 'Hidden'}
 * </div>
 */
export const useIntersectionObserver = <T extends Element>(options?: IntersectionObserverInit) => {
  const [isIntersecting, setIsIntersecting] = useState<boolean>(false);
  const targetRef = useRef<T | null>(null);

  useEffect(() => {
    const element = targetRef.current;
    if (!element) return;

    const observer = new IntersectionObserver(([entry]) => {
      setIsIntersecting(entry.isIntersecting);
    }, options);

    observer.observe(element);
    return () => observer.disconnect();
  }, [options]);

  return { targetRef, isIntersecting } as const;
};